Skip to content

Fix #3180: one row per step on undirected edges with different costs - #3191

Closed
AdityaRanaX wants to merge 5 commits into
pgRouting:developfrom
AdityaRanaX:issue-3180-undirected-asymmetric
Closed

AdityaRanaX wants to merge 5 commits into
pgRouting:developfrom
AdityaRanaX:issue-3180-undirected-asymmetric

Conversation

@AdityaRanaX

@AdityaRanaX AdityaRanaX commented Nov 12, 2026 •

Copy link
Copy Markdown

Fixes #3180.

Changes proposed

  • Updated include/cpp_common/path.hpp to generate only one output row per path step when rebuilding a path, instead of adding a row for every edge with the same ID.
  • Added regression tests in pgtap/astar/edge_cases/issue_3180.pg, pgtap/bdAstar/edge_cases/issue_3180.pg and pgtap/bdDijkstra/edge_cases/issue_3180.pg, covering the nine affected functions.
  • Added entries to the release notes in doc/src/release_notes.rst and NEWS.md.

How I found the issue

While testing an undirected graph, I noticed that pgr_bdDijkstra was returning a higher total cost than pgr_dijkstra for the same route.

I reproduced the issue using a small chain of six vertices and five edges. After comparing their results, I checked the other functions in the aStar, bdAstar and bdDijkstra families and found the same problem.

Why it happens

On an undirected graph, when cost and reverse_cost are different (and both are non-negative), pgRouting stores two internal edges with the same ID. This behaviour is documented in doc/src/pgRouting-concepts.rst.

The affected functions rebuild their paths using Path(graph, original, only_cost). During this process, the code looks for edges matching the current edge ID but adds a result row for every match instead of selecting just one.

As a result, each step appears twice (once with cost 7 and once with cost 2), so both costs are added to the total.

pgr_dijkstra is not affected because it builds its path differently.

What I changed

I updated the loop in path.hpp to select only one matching edge for each path step.

It first looks for an edge whose cost matches the cost used for that step. If no exact match is found, it selects the cheapest matching edge.

This follows the same selection logic already used by get_edge_id and keeps the original graph representation unchanged.

Test results

I tested the fix using a chain of five edges, each with cost = 7 and reverse_cost = 2. Both tables below hold the same 5 edges; only the table name differs.

Before the fix

Query:

SELECT *
FROM pgr_bdDijkstra(
    'SELECT id, source, target, cost, reverse_cost FROM edges_undirected_asym',
    1, 6, false
);

Actual output:

 seq | path_seq | start_vid | end_vid | node | edge | cost | agg_cost
-----+----------+-----------+---------+------+------+------+----------
   1 |        1 |         1 |       6 |    1 |    1 |    7 |        0
   2 |        2 |         1 |       6 |    1 |    1 |    2 |        7
   3 |        3 |         1 |       6 |    2 |    2 |    7 |        9
   4 |        4 |         1 |       6 |    2 |    2 |    2 |       16
   5 |        5 |         1 |       6 |    3 |    3 |    7 |       18
   6 |        6 |         1 |       6 |    3 |    3 |    2 |       25
   7 |        7 |         1 |       6 |    4 |    4 |    7 |       27
   8 |        8 |         1 |       6 |    4 |    4 |    2 |       34
   9 |        9 |         1 |       6 |    5 |    5 |    7 |       36
  10 |       10 |         1 |       6 |    5 |    5 |    2 |       43
  11 |       11 |         1 |       6 |    6 |   -1 |    0 |       45
(11 rows)

pgr_bdDijkstra returned 11 rows instead of 6, with a final accumulated cost of 45 instead of 10.

After the fix

Query:

SELECT *
FROM pgr_bdDijkstra(
    'SELECT id, source, target, cost, reverse_cost FROM chain_asym',
    1, 6, false
);

Actual output:

 seq | path_seq | start_vid | end_vid | node | edge | cost | agg_cost
-----+----------+-----------+---------+------+------+------+----------
   1 |        1 |         1 |       6 |    1 |    1 |    2 |        0
   2 |        2 |         1 |       6 |    2 |    2 |    2 |        2
   3 |        3 |         1 |       6 |    3 |    3 |    2 |        4
   4 |        4 |         1 |       6 |    4 |    4 |    2 |        6
   5 |        5 |         1 |       6 |    5 |    5 |    2 |        8
   6 |        6 |         1 |       6 |    6 |   -1 |    0 |       10
(6 rows)

After the fix, pgr_bdDijkstra returns the expected 6 rows with a total cost of 10, matching pgr_dijkstra.

Additional testing

  • The new regression tests fail on the original code (18 of 36 assertions) and pass after the fix.
  • Directed graphs and undirected graphs where cost = reverse_cost continue to pass before and after the change.
  • The full test suite passes: 521 files, 52,277 tests, 0 failures.
  • Regenerated docqueries for astar, bdAstar and bdDijkstra. No .result files changed.
  • Manually compared all 12 functions (the nine affected ones plus pgr_dijkstra, pgr_KSP and pgr_dijkstraVia). All 12 produced matching results on the tested graph.
  • Also ran the one-to-many, many-to-one, many-to-many and combinations overloads of the six path and cost functions on the same graph by hand. They matched pgr_dijkstra / pgr_dijkstraCost.
  • Also tested reverse traversal, one-way edges, self-loops, parallel edges with different IDs and equal costs.

GitHub Actions for the last commit: https://github.com/AdityaRanaX/my-pgrouting/actions

Not included

  • pgr_bdAstar has some separate issues that I plan to report in another issue.
  • Bidirectional functions returning zero rows when the entire route has a cost of zero is another separate issue and is not addressed here.

The Update Locale bot also added one commit containing locale-file updates.

@pgRouting/admins

Summary by CodeRabbit

  • Bug Fixes
    • Fixed A* and bidirectional A*/Dijkstra results for undirected graphs with differing forward and reverse edge costs. Returned routes no longer contain duplicate nodes or edges, and their costs are no longer calculated by adding both directional costs.
  • Documentation
    • Updated the 4.1.0 release notes to document this correction.

@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The path-reconstruction constructor now emits one row per step. It prefers a matching edge with the stored step cost and otherwise selects the cheapest match. New pgTAP tests cover affected A* and bidirectional routing variants. Release materials document issue #3180.

Changes

Path result correction

Layer / File(s) Summary
Select one edge per path step
include/cpp_common/path.hpp
The constructor prefers a matching edge whose cost equals the stored step cost. If none matches, it selects the cheapest matching edge.
Issue 3180 regression coverage
pgtap/astar/edge_cases/issue_3180.pg, pgtap/bdAstar/edge_cases/issue_3180.pg, pgtap/bdDijkstra/edge_cases/issue_3180.pg
Tests compare affected routing variants with Dijkstra results. They cover directed and equal-cost controls, heuristic cases where applicable, and repeated edge IDs.
Release notes and catalogs
NEWS.md, doc/src/release_notes.rst, locale/en/LC_MESSAGES/pgrouting_doc_strings.po, locale/pot/pgrouting_doc_strings.pot
The 4.1.0 release notes and catalogs describe the duplicate node and edge results for undirected graphs with differing costs.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested labels: Bug Fix

Suggested reviewers: cvvergara, robe2

Merge Risk: Minimal · up to b8d68

This change stops duplicated rows and inflated costs on undirected graphs whose forward and reverse costs differ. It adds regression tests and release notes, and no merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Fix #3180: one row per step on undirected edges with different costs" matches the main change. The raw summary and objectives show that path.hpp now emits one row per step for undirected ed…
Linked Issues check Passed Issue #3180 requires one output row per path step for the nine aStar, bdAstar and bdDijkstra functions on undirected graphs where cost and reverse_cost are non-negative and differ. The expected result…
Out of Scope Changes check Passed The whole-PR diff against the merge base touches include/cpp_common/path.hpp (the fix and the include it needs), pgTAP regression tests for the affected functions, and release-note entries in…
Full details: Title check

Explanation

The title "Fix #3180: one row per step on undirected edges with different costs" matches the main change. The raw summary and objectives show that path.hpp now emits one row per step for undirected edges with different cost and reverse_cost, which fixes the duplicated rows and inflated agg_cost in issue #3180. The title names the issue and the specific behavior. It is concise and does not use vague terms.

Full details: Linked Issues check

Explanation

Issue #3180 requires one output row per path step for the nine aStar, bdAstar and bdDijkstra functions on undirected graphs where cost and reverse_cost are non-negative and differ. The expected result for the reproduced five-edge chain is 6 rows and final agg_cost 10. At the reviewed head (b8d68a7), the Path(graph, original, only_cost) constructor in include/cpp_common/path.hpp resets its out-edge iterator for each path step. For each step, it skips out-edges whose id differs from p.edge. It selects the first edge whose cost equals p.cost and stops. If no exact match exists, it selects the cheapest matching edge. It then pushes one row. Before this change, every matching out-edge pushed a row, which duplicated steps and double-counted agg_cost. The constructor is used by include/astar/astar.hpp and include/cpp_common/bidirectional.hpp, which covers the affected functions. The PR adds pgTAP regression tests for these functions under pgtap/astar, pgtap/bdAstar and pgtap/bdDijkstra edge_cases. I did not run the tests. The author reports that they fail before the change and pass after it. The change does not alter directed graphs or equal-cost undirected graphs, because only one matching edge exists in those cases. No unmet coding requirement is found.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff against the merge base touches include/cpp_common/path.hpp (the fix and the <limits> include it needs), pgTAP regression tests for the affected functions, and release-note entries in NEWS.md and doc/src/release_notes.rst. These changes support the #3180 objective. The locale files (pgrouting_doc_strings.po and pgrouting_doc_strings.pot) gain the matching release-note entry. They come from a bot commit and are generated documentation tied to that note. No unrelated change is demonstrated. The PR states that separate pgr_bdAstar issues and the zero-cost empty-result behavior are not addressed, and the diff contains no changes for them.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the winding track,
One edge per step, no doubled stack.
The costs now match the path in view,
Tests trace the routes and controls too.
Release notes mark the fix in place.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 08a8ec39-ab80-4ce5-9be8-e4b96a8df2ba
Commits

Reviewing files that changed from the base of the PR and between 028e8a1 and b8d68a7.

Files selected for processing: 4

  • NEWS.md
  • doc/src/release_notes.rst
  • locale/en/LC_MESSAGES/pgrouting_doc_strings.po
  • locale/pot/pgrouting_doc_strings.pot

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@cvvergara cvvergara left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your solution is interesting.
Your pgtap tests are very very interesting and include the other functions that are silently affected.
Please work the pgtap tests first.

First do the file under tools/testers that has the currently duplicated code
(no name changes on the function names)
commit.
Then make the pgtap tests work ( you have to include the file figure it out)
commit.
Then make the now non duplicated code as much as possible self documented.

Maybe some of my comments do not apply once you have the common code set.

Then create more tables with the characteristics I mentioned somewhere.
(things might pass or fail with your solution)
if they fail then modify your solution.



/*
* Issue #3180: undirected graph where cost and reverse_cost differ

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have a lot of explanation to do in these pgtap files:

As a start: why? you didnt copy/paste the exact title of the issue

*
* On an undirected graph an edge whose cost and reverse_cost are both non
* negative and different is kept as two internal edges that share the same
* id. pgr_aStar, pgr_aStarCost and pgr_aStarCostMatrix returned a row for

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is about pgr_star why do you mention all three functions?

* negative and different is kept as two internal edges that share the same
* id. pgr_aStar, pgr_aStarCost and pgr_aStarCostMatrix returned a row for
* each of them, so every node and edge came back twice and agg_cost added
* both weights. The pgr_dijkstra family uses each edge once and is the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you mention pgr_dijkstra if it does not have a problem?

* both weights. The pgr_dijkstra family uses each edge once and is the
* reference here.
*
* The chain below costs 7 one way and 2 the other, so the cheapest route

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean by chain?

CREATE TEMP TABLE edges_3180 AS
SELECT * FROM (VALUES
(1::BIGINT, 1::BIGINT, 2::BIGINT, 7::FLOAT, 2::FLOAT, 0::FLOAT, 0::FLOAT, 1::FLOAT, 0::FLOAT),
(2::BIGINT, 2::BIGINT, 3::BIGINT, 7::FLOAT, 2::FLOAT, 1::FLOAT, 0::FLOAT, 2::FLOAT, 0::FLOAT),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a more simpler way to write the rows 2 to 5.
which is it?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, this table has all the edges have same cost & reverse cost
You are not testing with tables with edges (still asymmetrical) where between rows the cost & reverse cost varies
You are not testing with tables that have parallel edges with edge_id that are different.


/* the same four checks for one function: the bug, then the two controls */
CREATE OR REPLACE FUNCTION issue_3180_variant(
fn TEXT, ref TEXT, cols TEXT, verts TEXT, h0 TEXT, h5 TEXT)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm so reading forward down
cols is not columns (like of the columns passed to a function)
Those are the result columns the variant function will compare.
a better name for it is result_cols

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

verts = hmm, so they are the parameters they are not precisely vertices.

`1::BIGINT, 6::BIGINT',
'ARRAY[1, 6]::BIGINT[]',

vert_params would be a better name

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for h0 and h5

I allways see on the function call:
', 0, 1::FLOAT, 1::FLOAT', ', 5, 1::FLOAT, 1::FLOAT');

So its not the heuristic only its the heuristic + something else.

From what I see in this example call:

  RETURN QUERY SELECT * FROM issue_3180_variant('pgr_aStarCost', 'pgr_dijkstraCost',
      'start_vid, end_vid, agg_cost', '1::BIGINT, 6::BIGINT',
      ', 0, 1::FLOAT, 1::FLOAT', ', 5, 1::FLOAT, 1::FLOAT');

It can be simplified to:

  RETURN QUERY SELECT * FROM issue_3180_variant('pgr_aStarCost', 'pgr_dijkstraCost',
      'start_vid, end_vid, agg_cost', '1::BIGINT, 6::BIGINT');

Just because you are not using any other heiristic than 0 or 5

It can be simplified to:

  RETURN QUERY SELECT * FROM issue_3180_variant('pgr_aStarCost', 'pgr_dijkstraCost',
      'start_vid, end_vid, agg_cost', '1::BIGINT, 6::BIGINT', 0);  -- Using the 0 heuristic

Just because the 1::FLOAT, 1::FLOAT is allways used.

SELECT CASE WHEN min_version('4.1.0') THEN plan(13) ELSE plan(1) END;

/* builds: SELECT <cols> FROM <fn>('SELECT <incols> FROM <tbl>', <verts>, <flag><extra>) */
CREATE OR REPLACE FUNCTION issue_3180_q(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A general comment about issue_3180_q and issue_3180_variant
They seem to be repeated code on the three pgtap tests.
if its some functionality you need for more than one function the appropriate place in a file on tools/teststers. (please that is for general tests so no mention of issue_3180 is to be used.
Can be asymmetrical_tests.sql

/* :file: This file is part of the pgRouting project.
:copyright: Copyright (c) 2026-2026 pgRouting developers
:license: Creative Commons Attribution-Share Alike 3.0 https://creativecommons.org/licenses/by-sa/3.0 */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I Do like your tests,
They need work , please no AI involved.

msgid ":issue:`3101`: pgr_edgeColoring not building graph correctly"
msgstr ""

msgid ":issue:`3180`: On undirected graphs where cost and reverse_cost differ, pgr_aStar, pgr_aStarCost, pgr_aStarCostMatrix, pgr_bdAstar, pgr_bdAstarCost, pgr_bdAstarCostMatrix, pgr_bdDijkstra, pgr_bdDijkstraCost and pgr_bdDijkstraCostMatrix returned every node and edge twice, with both costs added up"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue title is not that

/* TODO(v4) add correct predecessor node */
path.push_back({m_end_id, -1, 0, 0, 0});
} else {
/*

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I (sorta) like your solution,
Where the problem is the the Path class is not catching the min parallel cost.

The sorta is because the Path has serious issues that have not been addressed, and the non spoken plan is to get rid of this class. And you are not going to address any issue on this class or attempt to get rid of this class.

I don't like your comment.
Self documented code is important.

You are talking about edges with the same id, what will happen when there are parallel edges with different id? and the other edge has a lower cost?

@cvvergara
cvvergara marked this pull request as draft November 19, 2026 18:11
@cvvergara
cvvergara requested a review from robe2 November 19, 2026 22:30
@AdityaRanaX

AdityaRanaX commented Nov 25, 2026 •

Copy link
Copy Markdown
Author

Closing this, since #3196 and #3197 fixes #3180 in a cleaner way: it keeps only the cheapest edge between two vertices when the graph is built, so parallel edges with different ids are handled too, and the Path class stays untouched. Thank you @cvvergara and @robe2 for reviewing my PR. The comments on self-documenting tests and on moving shared helpers to tools/testers were very useful for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Undirected graph with cost != reverse_cost: aStar, bdAstar and bdDijkstra functions return every node and edge twice

3 participants